package com.controler.joystick;

import com.licheedev.modbus4android.ModbusCallback;
import com.licheedev.modbus4android.ModbusParam;
import com.licheedev.modbus4android.ModbusWorker;
import com.licheedev.modbus4android.param.SerialParam;
import com.serotonin.modbus4j.ModbusMaster;

public class ModbusManager extends ModbusWorker {
    private static volatile ModbusManager sInstance;                      // 表示自己

    /*  获取自己 */
    public static ModbusManager get(){
        ModbusManager manager = sInstance;
        if (manager == null){
            synchronized (ModbusManager.class) {
                manager = sInstance;
                if (manager == null) {
                    manager = new ModbusManager();
                    sInstance = manager;
                }
            }
        }
        return manager;
    }

    public ModbusParam GenParameter(String path,int baudrate,int parity,int stopbit){
        ModbusParam param = SerialParam.create(path,baudrate).setDataBits(8).setParity(parity).setStopBits(stopbit).setTimeout(300).setRetries(2);
        return param;
    }
    /* 打开设备 */
    public boolean OpenDevice(ModbusParam param){
        if(get().isModbusOpened()){
            get().closeModbusMaster();
            return true;
        }
        get().init(param, new ModbusCallback<ModbusMaster>() {
            @Override
            public void onSuccess(ModbusMaster modbusMaster) {

            }

            @Override
            public void onFailure(Throwable tr) {

            }

            @Override
            public void onFinally() {

            }
        });
        return false;
    }

    /* 关闭设备 */
    public boolean CloseDevice(){
        if(get().isModbusOpened()){
            get().closeModbusMaster();
            return true;
        }
        return true;
    }

    private ModbusManager(){

    }

    public synchronized void release(){
        super.release();
        sInstance = null;
    }
}
